<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm" :disabled="!isHide">
      <el-row>
        <el-col :span="24">
          <el-form-item
            :label="!isDisplay ? '本周计划' : '下周计划'"
            prop="workPlan"
            :rules="
              isDisplay ? [{ required: true, message: $t('必填信息') }] : []
            "
          >
            <el-input
              v-model="form.workPlan"
              :readonly="!isDisplay"
              type="textarea"
              :placeholder="$t('请在这里填写...')"
              :autosize="{ minRows: 4, maxRows: 8 }"
              show-word-limit
              minlength="20"
              maxlength="2000"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-table
        style="margin-top:10px"
        tooltip-effect="darkTable"
        :data="form.weeklyList"
        border
        :span-method="arraySpanMethod"
        class="nowrapTable formTable"
      >
        <el-table-column :label="$t('记录日期')" align="center" prop="recordDate" width="150" show-overflow-tooltip>
          <template slot-scope="scope">
            <span style="font-size: 16px;">{{ parseTime(scope.row.recordDate) + ' ' + $t(getDateWeek(parseTime(scope.row.recordDate))) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('项目名称')" align="center" prop="dealId" width="250">
          <template slot-scope="scope">
            <el-form-item :prop="'weeklyList.' + scope.$index + '.dealId'">
              <el-select
                ref="selectDom"
                v-model="scope.row.dealId"
                filterable
                remote
                clearable
                :placeholder="$t('项目名称')"
                :remote-method="remoteMethod"
                :loading="optionLoading"
                @change="dealChange(scope.row)"
              >
                <el-option
                  v-for="item in filterDealList"
                  :key="item.id"
                  :label="item.dealName"
                  :value="item.id"
                />
              </el-select>

              <!-- <el-autocomplete
                v-model="scope.row.dealId"
                class="inline-input"
                :fetch-suggestions="querySearch"
                placeholder="请输入内容"
                :trigger-on-focus="false"
                @select="handleSelect($event,scope.$index)"
              >
                <template slot-scope="{ item }">
                  <div class="name">{{ item.dealName }}</div>
                </template>
              </el-autocomplete> -->
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('时长(小时)')" align="center" prop="duration" width="100">
          <template slot-scope="scope">
            <el-form-item
              :prop="'weeklyList.' + scope.$index + '.duration'"
              :rules="checkDate(scope.row.recordDate)?rules.duration:[]"
            >
              <el-input-number v-model="scope.row.duration" :min="0" :max="15" :controls="false" :precision="0" :placeholder="$t('时长')" />
            </el-form-item>
          </template>
        </el-table-column>
        <!-- <el-table-column :label="$t('是否驻场')" align="center" prop="site" width="150">
          <template slot-scope="scope">
            <el-form-item :prop="'weeklyList.' + scope.$index + '.site'">
              <el-radio-group v-model="scope.row.site">
                <el-radio
                  v-for="dict in siteOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{ $t(dict.dictLabel) }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </template>
        </el-table-column> -->
        <el-table-column :label="$t('工作完成情况')" align="center" prop="workCompletion">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('工作完成情况') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item
              :prop="'weeklyList.' + scope.$index + '.workCompletion'"
              :rules="scope.row.duration!=undefined?rules.workCompletion:[]"
            >
              <el-input
                v-model="scope.row.workCompletion"
                type="textarea"
                :placeholder="$t('工作完成情况')"
                :autosize="{ minRows: 1, maxRows: 4 }"
                show-word-limit
                minlength="20"
                maxlength="2000"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" width="100">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-circle-plus" @click="addWeekHandle(scope.$index, scope.row)" />
            <el-button type="text" icon="el-icon-delete-solid" @click="delWeekHandle(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <!-- 附件列表 -->
      <FileTable
        :list.sync="form.fileList"
        data-type="anxin-week"
      />
    </el-form>
    <div v-show="isHide" slot="footer" class="dialog-footer" style="text-align: right;">
      <save-btn has-permi="anxin:weekly" />
    </div>
  </div>
</template>

<script>
import { saveAnxinWeekly, getByYearWeek, delAnxinWeekly } from '@/api/anxin/weekly/anxinWeekly'
import { findDeal } from '@/api/base/deal/dealBase'
import moment from 'moment'

export default {
  components: {
  },
  data() {
    var strLengthCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('必填信息'))
      } else {
        if (value.length < 20) {
          callback(new Error('请最少输入20个字符'))
        }
        callback()
      }
    }
    return {
      optionLoading: false,
      filterDealList: [],
      // 是否驻场字典
      siteOptions: [], // 表单参数
      // 项目列表
      dealList: [],
      form: {
        weeklyList: [],
        fileList: [],
        workPlan: ''
      },
      // 遮罩层
      loading: false,
      // 表单校验
      rules: {
        workCompletion: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' },
          { validator: strLengthCheck, trigger: 'blur' }],
        duration: [
          { required: true, message: '请填时长', trigger: 'blur' }
        ]
      },
      isHide: true
    }
  },
  computed: {
    isDisplay() {
      var nowDay = moment(new Date()).format('YYYY-MM-DD') // 当前日期
      const currentDay = this.getDateWeek(nowDay)
      if (currentDay === '周五' || currentDay === '周六' || currentDay === '周日') {
        return true
      }
      return false
    }
  },
  created() {
    this.getDicts('sys_yes_no').then(response => {
      this.siteOptions = response.data
    })
    findDeal().then(response => {
      this.dealList = response.data
    })
  },
  mounted() {
    this.$bus.$emit('async_done')
  },
  methods: {
    // 初始化数据
    init(data) {
      console.log('周报data', data)
      this.loading = true
      this.form.weeklyList = []
      if (data && data.id && data.yearWeek) {
        getByYearWeek(data).then(response => {
          this.form.workPlan = response.data.workPlan
          this.form.weeklyList = response.data.weeklyList
          this.form.fileList = response.data.fileList
          var weekIds = []
          this.form.weeklyList.forEach(e => {
            if (e.duration == null) {
              e.duration = undefined
            }
            weekIds.push(e.dealId)
          })
          findDeal().then(response => {
            this.dealList = response.data
            const ids = []
            const strs = []
            this.dealList.forEach(ele => {
              if (weekIds.includes(ele.id)) {
                ids.push(ele.id)
                strs.push(ele.dealName)
              }
            })
            this.filterDealList = []
            // 清空
            this.$refs.selectDom.cachedOptions = []
            for (let i = 0; i < strs.length; i++) {
              const obj = {
                id: ids[i],
                dealName: strs[i]
              }
              this.filterDealList.push(obj)
              this.$refs.selectDom.cachedOptions.push({
                currentLabel: strs[i],
                currentValue: ids[i],
                label: strs[i],
                value: ids[i]
              })
            }
            this.loading = false
          })
        })
      } else if (data && data.yearWeek) {
        // 补录周报
        const date = new Date(this.getMonday(data.date))
        const yearWeek = this.getWeek(date)
        const queryParam = {
          yearWeek: yearWeek
        }
        getByYearWeek(queryParam).then(response => {
          this.form.workPlan = response.data.workPlan
        })
        for (let i = 0; i < 7; i++) {
          const weekly = {
            id: undefined,
            recordDate: i === 0 ? this.parseTime(date) : this.parseTime(new Date(date.setDate(date.getDate() + 1))),
            dealId: undefined,
            duration: undefined,
            site: undefined,
            workCompletion: '1.\n' +
              '2.',
            yearWeek: data.yearWeek
          }
          if (i >= 5) {
            weekly.workCompletion = '无'
          }
          this.form.weeklyList.push(weekly)
        }
        this.form.fileList = []
        this.loading = false
      } else {
        const yearWeek = this.getWeek(new Date())
        const queryParam = {
          yearWeek: yearWeek
        }
        getByYearWeek(queryParam).then(response => {
          this.form.workPlan = response.data.workPlan
        })
        const date = new Date(this.getMonday(new Date()))
        for (let i = 0; i < 7; i++) {
          const weekly = {
            id: undefined,
            recordDate: i === 0 ? this.parseTime(date) : this.parseTime(date.setDate(date.getDate() + 1)),
            dealId: undefined,
            duration: undefined,
            site: undefined,
            workCompletion: '1.\n' +
              '2.',
            yearWeek: yearWeek
          }
          if (i >= 5) {
            weekly.workCompletion = '无'
          }
          this.form.weeklyList.push(weekly)
        }
        this.form.fileList = []
        this.loading = false
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        recordDate: undefined,
        dealId: undefined,
        duration: 0,
        site: '0',
        workCompletion: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.form.weeklyList = []
      this.form.fileList = []
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      this.form.weeklyList = []
      this.form.fileList = []
      // 关闭form页面
      this.$parent.$parent.formOpen = false
      // 刷新list页面
      this.$parent.$parent.getList()
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          console.log(this.form)
          saveAnxinWeekly(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              this.closeForm()
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      })
    },
    // 获取日期d是哪一年的第几周
    getWeek(d) {
      // 截掉时分秒保留整数天
      var date = new Date((d || new Date()))
      // 设置日期为当前周周四
      date.setDate(date.getDate() + (4 - (date.getDay() || 7)))
      var year = date.getFullYear()

      var firstDate = new Date(year, 0, 1)

      firstDate.setDate(firstDate.getDate() + (4 - (firstDate.getDay() || 7)))
      // 当年第一天早于周四第一周延后七天
      if (firstDate.getFullYear() < year) {
        firstDate.setDate(firstDate.getDate() + 7)
      }
      // 计算当前周和第一周之间周数差
      var week = Math.ceil(((date - firstDate) / 86400000 + 1) / 7)
      return year + '' + ('0' + week).substr(-2)
    },
    // 获取日期dd所处周的周一日期
    getMonday(dd) {
      var date = new Date((dd || new Date()))
      var week = date.getDay() // 获取时间的星期数
      var minus = week ? week - 1 : 6
      date.setDate(date.getDate() - minus) // 获取minus天前的日期
      var y = date.getFullYear()
      var m = date.getMonth() + 1 // 获取月份
      var d = date.getDate()
      return y + '-' + m + '-' + d
    },
    // 根据日期dateString获取星期几
    getDateWeek(dateString) {
      var dateArray = dateString.split('-')
      var date = new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2])
      return '周' + '日一二三四五六'.charAt(date.getDay())
    },
    isHideInit(isHideFalg) {
      if (isHideFalg) {
        this.isHide = false
      } else {
        this.isHide = true
      }
    },
    dealChange(row) {
      // 1. 选择项目时 按照选怎的时间点为基点之后时间全部改变
      this.form.weeklyList.forEach(day => {
        if (this.CompareDate(day.recordDate, row.recordDate) && (!row.isTempAdd)) {
          day.dealId = row.dealId
        }
      })
    },
    // 添加
    addWeekHandle(index, item) {
      const row = {
        recordDate: item.recordDate,
        dealId: item.dealId,
        yearWeek: item.yearWeek,
        duration: undefined,
        workCompletion: '1.\n' + '2.',
        isTempAdd: true // 新增临时变量用户新增行时判断
      }
      if (!(this.form.weeklyList instanceof Array)) {
        this.$set(this.form, 'weeklyList', [])
      }
      this.$nextTick(() => {
        this.form.weeklyList.splice(index + 1, 0, row)
      })
    },
    // 删除
    delWeekHandle(index, row) {
      if (!this.isUnique(this.form.weeklyList, row, index)) {
        this.$message({ message: '最少保留一条', type: 'warning' })
        return
      }
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        })
          .then(function() {
            return delAnxinWeekly(id)
          })
          .then(() => {
            this.form.weeklyList.splice(index, 1)
            return this.msgSuccess(this.$t('删除成功'))
          })
          .catch(function() { })
      } else {
        this.form.weeklyList.splice(index, 1)
      }
    },
    arraySpanMethod({ rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        const spanArr = this.rowspan()
        for (let i = 0; i < spanArr.length; i++) {
          const _row = spanArr[rowIndex]
          return {
            rowspan: _row,
            colspan: 1
          }
        }
      }
    },
    rowspan() {
      // 二维数组，用于存放单元格合并规则
      const spanArr = []
      // 用于存储相同项的开始index
      let position = 0
      this.form.weeklyList.forEach((item, index) => {
        if (index === 0) {
          spanArr.push(1)
          position = 0
        } else {
          if (
            this.form.weeklyList[index].recordDate ===
            this.form.weeklyList[index - 1].recordDate
          ) {
            spanArr[position] += 1 // 有相同项
            spanArr.push(0) // 名称相同后往数组里面加一项0
          } else {
            spanArr.push(1) // 同列的前后两行单元格不相同
            position = index
          }
        }
      })
      return spanArr
    },
    CompareDate(d1, d2) {
      return ((new Date(d1.replace(/-/g, '\/'))) >= (new Date(d2.replace(/-/g, '\/'))))
    },
    isUnique(arr, value, index) {
      const newArr = JSON.parse(JSON.stringify(arr))
      newArr.splice(index, 1)
      const exist = newArr.find(item => {
        return item.recordDate === value.recordDate
      })
      return exist
    },
    checkDate(d) {
      var date = this.formatDate(new Date(d))
      var dateArray = date.split('-')
      var day = new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2])
      if (day.getDay() === 0 || day.getDay() === 6) {
        return false
      }
      var day1 = new Date(date).getTime()
      var day2 = new Date().getTime()
      return day1 <= day2
    },
    formatDate(date) {
      var myyear = date.getFullYear()
      var mymonth = date.getMonth() + 1
      var myweekday = date.getDate()
      if (mymonth < 10) {
        mymonth = '0' + mymonth
      }
      if (myweekday < 10) {
        myweekday = '0' + myweekday
      }
      return myyear + '-' + mymonth + '-' + myweekday
    },
    querySearch(queryString, cb) {
      var restaurants = this.dealList
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      console.log('results', results)
      cb(results)
    },
    handleSelect(item, row) {
      console.log(item, row)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.dealName.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    remoteMethod(query) {
      if (query !== '') {
        this.optionLoading = true
        setTimeout(() => {
          this.optionLoading = false
          this.filterDealList = this.dealList.filter(item => {
            return item.dealName.toLowerCase()
              .indexOf(query.toLowerCase()) > -1
          })
        }, 400)
      } else {
        this.filterDealList = []
      }
    }
  }

}
</script>
<style scoped>
.name {
  text-overflow: ellipsis;
  overflow: hidden;
}
</style>
